

#include "QMC5883.h"
extern I2C_HandleTypeDef hi2c1;

/***************************************************************************/
uint8_t QMC5883_Init()  //初始化模块
{
        uint8_t uChipID = 0;    
		uint8_t qmc5883_reset = 1;
	    uint8_t qmc5883_CONF1 = CONF1;
		uint8_t qmc5883_CONF2 = CONF2;
        // 设备复位，检查设备
	    HAL_I2C_Mem_Write(&hi2c1,QMC5883_DEV,0x0B ,I2C_MEMADD_SIZE_8BIT, &qmc5883_reset,1,100);
		HAL_I2C_Mem_Write(&hi2c1,QMC5883_DEV,QMC5883P_REG_CONF1 ,I2C_MEMADD_SIZE_8BIT, &qmc5883_CONF1,1,100);
		HAL_I2C_Mem_Write(&hi2c1,QMC5883_DEV,QMC5883P_REG_CONF2 ,I2C_MEMADD_SIZE_8BIT, &qmc5883_CONF2,1,100);
	    if(HAL_I2C_Mem_Read(&hi2c1,QMC5883_DEV,0x0D,I2C_MEMADD_SIZE_8BIT,&uChipID,1,100)==0  &&  uChipID == 0XFF){
                return 0;
         }
//        MY_IIC_WriteByte(QMC5883_DEV,0x0B,0X01);               //复位
//        MY_IIC_WriteByte(QMC5883_DEV,QMC5883L_REG_CONF1,CONF1);    //配置控制器1
//         if(MY_IIC_ReadByte(QMC5883_DEV,0x0D,&uChipID)==0  &&  uChipID == 0XFF){
//                return 0;
//         }
         else return 1;
}

/***************************************************************************/

uint8_t QMC5883_GetData(float *QMC_data)         //数据获取
{   
        uint8_t DRDY;
        uint8_t buf[6];
		HAL_I2C_Mem_Read(&hi2c1,QMC5883_DEV,0X9,I2C_MEMADD_SIZE_8BIT,&DRDY,1,100);
//        MY_IIC_ReadBits(QMC5883_DEV,0X06,3,3,&DRDY);       //读就绪寄存器  0000 0010
            
     if(DRDY&0x01){                                          //如果数据就绪且没溢出&& OVL==0
                    DRDY=0;
					HAL_I2C_Mem_Read(&hi2c1,QMC5883_DEV,0x1,I2C_MEMADD_SIZE_8BIT,buf,6,100);
//                    MY_IIC_ReadBytes(QMC5883_DEV,0x0,6,buf);       // 读取数据部分是前六个寄存器0x0~0x5
                        
                    int16_t data0= (((int16_t)buf[1]) << 8) | buf[0];
                    int16_t data1=  (((int16_t)buf[3]) << 8) | buf[2];
                    int16_t data2=  (((int16_t)buf[5] )<< 8) | buf[4];
					QMC_data[0] = (float)data0 / 12000.0f  ;
					QMC_data[1] = (float)data1 / 12000.0f  ;
					QMC_data[2] = (float)data2 / 12000.0f  ;

		 
                    return 0;       //成功
                 } 
        else return 1;   //失败 
}




